package com.crane.oss.sys.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.oss.enums.PartyTypeEnum;
import com.crane.oss.enums.UserTypeEnum;
import com.crane.oss.sys.bean.request.role.AddPartyRoleRequest;
import com.crane.oss.sys.bean.request.role.QueryPartyRoleRequest;
import com.crane.oss.sys.bean.request.role.UpdatePartyRoleRequest;
import com.crane.oss.sys.bean.resp.PartyRoleBean;
import com.crane.oss.sys.dao.PartyRoleDao;
import com.crane.oss.sys.model.PartyRole;
import com.crane.oss.sys.service.PartyRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("partyRoleService")
public class PartyRoleServiceImpl implements PartyRoleService {

    private static final Logger logger = LoggerFactory.getLogger(PartyRoleServiceImpl.class);

    @Resource
    protected PartyRoleDao partyRoleDao;

    @Override
    public PartyRoleBean queryPartyRole(Long id) {
        logger.info("PartyRoleServiceImpl queryViewBean id={}", id);
        PartyRole partyRole = partyRoleDao.selectById(id);
        if (null == partyRole) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "partyRole");
        }
        PartyRoleBean partyRoleBean = new PartyRoleBean();
        BeanUtil.copyProperties(partyRole, partyRoleBean);
        return partyRoleBean;
    }

    @Override
    public IPage<PartyRoleBean> queryList(QueryPartyRoleRequest queryRequest) {
        logger.info("PartyRoleServiceImpl queryList queryRequest={}", JSON.toJSON(queryRequest));
        IPage<PartyRole> page = partyRoleDao.selectPage(new Page<>(queryRequest.getPageNo(), queryRequest.getPageSize()),
                Wrappers.lambdaQuery(PartyRole.class)
                        .eq(null!=queryRequest.getPartyType(),PartyRole ::getPartyType,queryRequest.getPartyType())
                        .eq(null!=queryRequest.getUserType(),PartyRole::getUserType,queryRequest.getUserType()));
        return page.convert(u -> {
            PartyRoleBean v = new PartyRoleBean();
            BeanUtils.copyProperties(u, v);
            v.setUserName(UserTypeEnum.getUserTypeName(u.getUserType()));
            v.setPartyTypeName(PartyTypeEnum.getPartyTypeName(u.getPartyType()));
            return v;
        });
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(AddPartyRoleRequest addRequest) {
        logger.info("PartyRoleServiceImpl save request={}", JSON.toJSON(addRequest));

        Map<String, Object> req = new HashMap<>();
        req.put("partyType", addRequest.getPartyType());
        req.put("userType", addRequest.getUserType());
        int count = partyRoleDao.selectCount(Wrappers.lambdaQuery(PartyRole.class)
                .eq(PartyRole ::getPartyType,addRequest.getPartyType())
                .eq(PartyRole ::getUserType,addRequest.getUserType()));
        if (count != 0) {
            throw new AppException(BasicErrorCode.ENTITY_IS_EXISTS, "机构类型对应角色");
        }
        PartyRole partyRole = new PartyRole();
        BeanUtil.copyProperties(addRequest, partyRole);
        partyRole.setCreateTime(new Date());
        return partyRoleDao.insert(partyRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(UpdatePartyRoleRequest updateRequest) {
        logger.info("PartyRoleServiceImpl update request={}", JSON.toJSON(updateRequest));
        PartyRole partyRole = partyRoleDao.selectById(updateRequest.getId());
        if (null == partyRole) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "partyRole");
        }
        partyRole.setRoleId(updateRequest.getRoleId());
        partyRole.setUpdateTime(new Date());
        return partyRoleDao.updateById(partyRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        logger.info("PartyRoleServiceImpl delete id={}", id);
        return partyRoleDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByRoleId(Long roleId) {
        logger.info("PartyRoleServiceImpl deleteByRoleId roleId={}", roleId);
        return partyRoleDao.delete(Wrappers.lambdaQuery(PartyRole.class).eq(PartyRole::getRoleId,roleId));
    }
}
